<template>
  <section>
    <el-card class="margin-top">
      <div slot="header" class="clearfix relative">
        <el-row class="flex align-center ">
          <el-col>
            <span class="title-icon margin-right">货物信息</span>

            <el-button
              type="primary"
              size="mini"
              icon="el-icon-download"
              @click="downloadCargoInfo"
            >
              导出货物信息
            </el-button>
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-upload2"
              @click="uploadDialog = true"
            >
              导入货物信息
            </el-button>
          </el-col>
          <el-col>
            <el-button
              v-if="isEdit"
              type="success"
              size="mini"
              class="header-save-btn"
              @click="changeCargoInfo"
            >
              保存
            </el-button>
          </el-col>
        </el-row>
      </div>

      <div>
        <hot-table ref="hotTable" :settings="hotSettings" :data="goodsInfo" />
      </div>
    </el-card>

    <ImportPop
      :upload-dialog.sync="uploadDialog"
      :dialog-title="`批量导入货物信息`"
      :action-url="`/abroad/waybills/batchUploadGoodsInfoData`"
      :file-name="`goodsInfoFile`"
      @uploadCb="uploadCargoInfo"
    />
  </section>
</template>

<script>
import ImportPop from '@/components/ImportPop'
import { HotTable } from '@handsontable/vue'
// import Handsontable from 'handsontable'

import 'handsontable/languages/zh-CN'
import globalData from '@/utils/config'
import {
  downLoadGoodsInfo,
  batchSaveOrUpdateGoodsInfo
} from '@/api/abroadWaybill'
export default {
  name: 'CargoInfo',
  components: {
    HotTable,
    ImportPop
  },
  props: {
    goodsInfo: {
      type: Array,
      default: function(params) {
        return [{}]
      }
    },
    oldGoodsInfo: {
      type: Array,
      default: function(params) {
        return [{}]
      }
    },
    actionUrl: {
      type: String,
      default: ''
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    waybillId: [String, Number]
  },

  data() {
    // const myNumeric = (value, callback) => {
    //   if (value <= 0) {
    //     callback(false)
    //   } else {
    //     callback(true)
    //   }
    // }
    return {
      uploadDialog: false,

      waybillGoodsInfos: [{}, {}, {}, {}, {}],
      hotSettings: {
        rowHeaders: true, // 行表头
        stretchH: 'all', // 所有列宽小于表宽时,填充满整个表 all（所有列填充）/last（最后一列）/none(不填充)
        licenseKey: globalData.licensekey,
        // 定义表结构
        colHeaders: [
          '<i style="color:red;margin-right:3px">*</i>旧FNSKU',
          '店铺链接	',
          '<i style="color:red;margin-right:3px">*</i>品名',
          '<i style="color:red;margin-right:3px">*</i>产品个数',
          '箱数',
          '<i style="color:red;margin-right:3px">*</i>重量',
          '<i style="color:red;margin-right:3px">*</i>体积'
        ],
        width: '100%',
        height: 'auto',

        columns: [
          {
            data: 'sku', // 指定所指列
            width: 100,
            allowEmpty: false,
            type: 'text' // 类型
          },
          {
            data: 'sellUrl',
            width: 100,
            type: 'text'
          },
          {
            data: 'productName',
            width: 100,
            allowEmpty: false,
            type: 'text'
          },
          {
            data: 'productNum',
            width: 100,
            allowEmpty: false,
            type: 'numeric',
            className: 'htLeft ',
            numericFormat: {
              pattern: '0'
            }
          },
          {
            data: 'productCtns',
            width: 100,
            type: 'numeric',
            className: 'htLeft ',
            numericFormat: {
              pattern: '0'
            }
          },
          {
            data: 'productWeight',
            width: 100,
            allowEmpty: false,
            // validator: myNumeric,
            type: 'numeric',
            numericFormat: {
              pattern: '0'
            }
          },
          {
            data: 'productVolume',
            width: 100,
            allowEmpty: false,
            type: 'numeric',
            numericFormat: {
              pattern: '0.000'
            }
          }
        ],
        tableClassName: ['first-class-name', 'second-class-name'],
        language: 'zh-CN',
        contextMenu: ['row_above', 'row_below', 'remove_row', 'alignment'], // 开启右键菜单
        beforeRemoveRow: (index, amount, physicalRows, source) => {
          if (this.goodsInfo.length === 1) {
            const arr = []
            arr.push({ waybillId: this.waybillId ? this.waybillId : null })
            this.$emit('update:goodsInfo', arr)
          }
        },
        afterCreateRow: (index, amount, source) => {
          const arr = [...this.goodsInfo]
          arr[index].waybillId = this.waybillId ? this.waybillId : null
          this.$emit('update:goodsInfo', arr)
        }
      }
    }
  },
  watch: {
    goodsInfo: {
      handler(newValue, oldValue) {
        if (newValue.length === 0) {
          this.$emit('update:goodsInfo', [{}])
        }
      }
      // immediate: true,
      // deep: true
    }
  },
  methods: {
    checkRate(input) {
      var re = /^[0-9]+.?[0-9]*/ //判断字符串是否为数字//判断正整数/[1−9]+[0−9]∗]∗/
      if (!re.test(nubmer)) {
        alert(`请输入数字`)
      }
    },
    digitUppercase(n) {
      let fraction = ['角', '分']
      let digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖']
      let unit = [
        ['元', '万', '亿'],
        ['', '拾', '佰', '仟']
      ]
      let head = n < 0 ? '欠' : ''
      n = Math.abs(n)
      let s = ''
      for (let i = 0; i < fraction.length; i++) {
        s += (
          digit[
            Math.floor(
              (Math.floor(n * 1000 * 10 * Math.pow(10, i)) % (10 * 1000)) / 1000
            )
          ] + fraction[i]
        ).replace(/零./, '')
      }
      s = s || '整'
      n = Math.floor(n)
      for (let i = 0; i < unit[0].length && n > 0; i++) {
        let p = ''
        for (let j = 0; j < unit[1].length && n > 0; j++) {
          p = digit[n % 10] + unit[1][j] + p
          n = Math.floor(n / 10)
        }
        s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s
      }
      return (
        head +
        s
          .replace(/(零.)*零元/, '元')
          .replace(/(零.)+/g, '零')
          .replace(/^整$/, '零元整')
      )
    },
    closeDialog() {
      this.uploadDialog = false
    },
    async downloadCargoInfo() {
      if (this.waybillId) {
        this.$store.dispatch('app/toggleDialog', true)

        const data = await downLoadGoodsInfo({
          waybillId: this.waybillId
        })

        if (data.fileName) {
          window.open(globalData.fileUrl + data.fileName)
        } else {
          this.$message.error(data.errorMesage)
        }

        this.$store.dispatch('app/toggleDialog', false)
      } else {
        //
        const link = document.createElement('a') // 生成一个a标签。
        link.href = './excel/abroad_goods_info.xlsx' // href属性指定下载链接
        link.click() // click()事件触发下载
      }
    },
    uploadCargoInfo(file) {
      console.log('uploadCargoInfo', file)
      for (const i of file.abroadWaybillGoodsInfos) {
        i.waybillId = this.waybillId
      }
      // const list = [
      //   ...this.goodsInfo,
      //   ...file.abroadWaybillGoodsInfos
      // ].filter(x => this.checkRowsEmpty(x))
      this.$emit('update:goodsInfo', file.abroadWaybillGoodsInfos)
    },
    checkRowsEmpty(rows) {
      if (rows === null) {
        return false
      }

      for (const i in rows) {
        if (i !== 'waybillId' && rows[i] !== null && rows[i] !== '') {
          console.log('rows[i] :>> ', rows[i])
          return true
        }
      }

      return false
    },
    changeCargoInfo() {
      for (const i of this.$refs.hotTable.data) {
        if (
          !i.sku ||
          !i.productName ||
          !i.productNum ||
          !i.productWeight ||
          !i.productVolume
        ) {
          this.$message.error('请填写必填信息')
          return
        }
      }
      // TODO 保存操作
      this.saveInfo()
    },
    async saveInfo() {
      this.$store.dispatch('app/toggleDialog', true)

      // 标记已删除数据
      // const arr = []
      // for (const i of this.oldGoodsInfo) {
      //   const target = this.goodsInfo.find(x => x.id === i.id)
      //   console.log('target :>> ', target)
      //   if (!target) {
      //     i.isDel = true
      //     arr.push(i)
      //   }
      // }
      const params = [...this.goodsInfo]
      for (let i of this.goodsInfo) {
        if (!i.waybillId) {
          i.waybillId = this.waybillId
        }
      }

      const { code, message } = await batchSaveOrUpdateGoodsInfo({
        waybillGoodsInfos: params
      })

      if (code === 200) {
        this.$message({
          type: 'success',
          message: '保存成功'
        })
      } else if (code === 400) {
        this.$message.error('参数类型有误，重量只能为正实数')
      } else {
        this.$message.error(message)
      }
      this.$store.dispatch('app/toggleDialog', false)
    }
  }
}
</script>

<style lang="scss" scoped>
.relative {
  .absolute {
    right: 10px;
    top: -40%;
  }
}
</style>
